package com.mooc.apigateway.service;

import com.google.common.collect.Lists;
import com.mooc.apigateway.dao.UserDao;
import com.mooc.apigateway.model.User;
import com.mooc.apigateway.utils.BeanHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户登录，注册，个人信息服务
 *
 */
@Service
public class AccountService {

    @Value("${domain.name}")
    private String domainName;

    @Autowired
    private FileService fileService;

    @Autowired
    private UserDao userDao;

    public boolean isExist(String email){
        return getUser(email) != null;
    }

    private User getUser(String email) {
        User queryUser = new User();
        queryUser.setEmail(email);
        List<User> users = getUserByQuery(queryUser);
        if(!users.isEmpty()){
            return users.get(0);
        }
        return null;
    }

    private List<User> getUserByQuery(User queryUser) {
        return userDao.getUserList(queryUser);
    }

    public boolean addAccount(User account) {
        if(account.getAvatarFile() != null){
            List<String> imags = fileService.getImgPaths(Lists.newArrayList(account.getAvatarFile()));
            account.setAvatar(imags.get(0));
        }
        account.setEnableUrl("http://" + domainName + "/accounts/verify");
        BeanHelper.setDefaultProp(account, User.class);
        userDao.addUser(account);
        return true;
    }

    public boolean enable(String key){
        return userDao.enable(key);
     }


    public User auth(String username, String password) {
          if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
              return null;
          }
        User user = new User();
        user.setEmail(username);
        user.setPasswd(password);
        try {
            user = userDao.authUser(user);
        } catch (Exception e) {
           return null;
        }
        return user;

    }


    public void logout(String token) {
        userDao.logout(token);
    }




}
